package com.wf.course.service.impl;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.utils.page.PageBean;
import com.wf.course.dao.ICardCourseRelationMapper;
import com.wf.course.dao.IVipCardMapper;
import com.wf.course.model.ad.VipCard;
import com.wf.course.service.IVipCardService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;

@Service
@Transactional(rollbackFor=Exception.class)
public class IVipCardServiceImpl implements IVipCardService{
	
	@Autowired
	private IVipCardMapper mapper;
	@Autowired
	private ICardCourseRelationMapper ccrMapper;

	@Override
	public void indexInfo(PageBean<VipCard> pageBean) {
		// TODO Auto-generated method stub
		pageBean.setResults(this.mapper.queryList(pageBean));
		pageBean.setTotalCount(this.mapper.getTotalCount(pageBean));
	}

	@Override
	public void saveOrUpdateVipCard(VipCard vipCard,MultipartFile imgFile) {
		// TODO Auto-generated method stub
		
		//添加
		if(vipCard.getId()==null){
			//创建时间
		 
			if (!imgFile.isEmpty()) {
				String cardImgUrl = "";
				try {
					cardImgUrl = OSSUtil.addFile(imgFile, "wf_course/imgPath", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				vipCard.setCardImg(cardImgUrl);
			}
			this.mapper.saveVipCard(vipCard);
		}else{
		 //修改
			

			if (imgFile.getSize() != 0) {
				VipCard card = mapper.queryVipCardById(vipCard.getId());
				try{
					if(StringUtils.isNotBlank(card.getCardImg())){
						// 删除原来图片
						OSSUtil.delete(card.getCardImg(), Constants.IGM_BUCKET);
					}
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				// 重新上传
				// 上传
				String cardImgUrl = "";
				try {
					cardImgUrl = OSSUtil.addFile(imgFile, "wf_course/imgPath", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				vipCard.setCardImg(cardImgUrl);
			}
			
			
		  this.mapper.updateVipCard(vipCard);
			
		}
		
	}

	@Override
	public VipCard queryVipCardById(Integer id) {
		// TODO Auto-generated method stub
		return this.mapper.queryVipCardById(id);
	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub
		//删除年卡
		this.mapper.deleteById(id);
		//删除年卡关联的课程
		this.ccrMapper.deleteByCardId(id);
	}

	 
	@Override
	public List<VipCard> queryVipCards(){
		return this.mapper.queryVipCards();
	}
	@Override
	public void updateCardSaleNum(VipCard vipCard){
		this.mapper.updateCardSaleNum(vipCard);
	}

	
}
